using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEditor;
using static UnityEngine.GraphicsBuffer;

public class PlayerController : MonoBehaviour
{
    public CameraFollow cameraFollow;//相机

    public float moveSpeed = 5f;
    public bool isLocalPlayer = false;
    public string playerId = "";

    private NetworkManager networkManager;
    private Vector3 lastSentPosition;
    private float positionUpdateThreshold = 0.1f;  // 位置更新阈值
    private float lastSendTime = 0f;
    private float sendInterval = 0.05f;  // 限制发送频率

    // 扩展特性 - 可以根据需要自定义玩家属性
    public float rotateSpeed = 400f;//坦克身体旋转速度
    public float health = 100f;
    public int score = 0;
    public GameObject bulletSpawnPoint;  // 在Inspector中设置炮弹生成点
    public float shootCooldown = 0.5f;   // 射击冷却时间
    public string team = "";             // 队伍标识 "A" 或 "B"'

    //旋转
    public float sensitivity = 1f; // 旋转灵敏度
    public string childName = "GunBarrel"; // 子对象名称
    private Transform childTransform;
    public LayerMask groundLayer; // 地面层
    public float GunBarrelRotateSpeed;//炮塔旋转速度
    private Quaternion currentTargetRotation;

    // 特效
    public GameObject deathEffect;       // 死亡特效
    public GameObject hitEffect;         // 被击中特效
    public GameObject respawnEffect;     // 复活特效

    // 状态
    public bool isDead = false;

    private float lastShootTime = 0f;
    private float lastSentRotation;
    private GameManager gameManager;
    private LayerMask allLayers = ~0;

    void Start()
    {
        networkManager = GameObject.Find("NetworkManager").GetComponent<NetworkManager>();
        gameManager = GameManager.Instance;

        lastSentPosition = transform.position;
        lastSentRotation = transform.eulerAngles.y;

        //炮塔查找
        childTransform = transform.Find(childName);

        // 验证是否为当前对象的子对象
        if (childTransform == null)
        {
            Debug.LogError($"未找到名为 {childName} 的子对象！");
            return;
        }

        // 更新UI
        UpdateUI();

        //摄像机附着
        AttachCamera();
        //Cursor.visible = false;

        // 如果是本地玩家，锁定并隐藏鼠标
        if (isLocalPlayer)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }
    }

    void Update()
    {
        // 不处理死亡状态的玩家
        if (isDead) return;

        // 只有本地玩家可以控制
        if (!isLocalPlayer) return;

        // 如果游戏未开始，禁止移动
        //if (gameManager != null && !gameManager.gameInProgress) return;

        // --- 移动控制 ---
        float move = Input.GetAxis("Vertical"); // W/S
        float rotate = Input.GetAxis("Horizontal"); // A/D

        // 只允许前进/后退，不允许左右平移
        Vector3 moveDir = transform.up * move * moveSpeed * -Time.deltaTime;
        transform.position += moveDir;

        // A/D 控制Y轴旋转
        //transform.Rotate(0, rotate * rotateSpeed * Time.deltaTime, 0);
        transform.Rotate(0, 0, rotate * rotateSpeed * Time.deltaTime);

        float currentRotY = transform.eulerAngles.y;
        // 判断是否需要同步位置或旋转
        if ((Vector3.Distance(transform.position, lastSentPosition) > positionUpdateThreshold || Mathf.Abs(currentRotY - lastSentRotation) > 0.5f) && Time.time - lastSendTime > sendInterval)
        {
            networkManager.SendMoveMessage(transform.position, currentRotY);
            lastSentPosition = transform.position;
            lastSentRotation = currentRotY;
            lastSendTime = Time.time;
        }

        //炮塔旋转
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        // 使用 allLayers 检测所有物体，并添加距离限制（例如1000米）
        if (Physics.Raycast(ray, out hit, 1000f, allLayers))
        {
            // 仅处理带有 BoxCollider 的物体
            if (hit.collider is BoxCollider)
            {
                Debug.Log("击中带有 BoxCollider 的物体: " + hit.collider.gameObject.name);

                // 计算物体到鼠标点击位置的方向
                Vector3 lookDirection = hit.point - transform.position;
                lookDirection.y = 0; // 保持水平方向

                if (lookDirection != Vector3.zero)
                {
                    // 动态更新目标旋转
                    float targetAngle = Mathf.Atan2(lookDirection.x, lookDirection.z) * Mathf.Rad2Deg;
                    currentTargetRotation = Quaternion.Euler(-90, targetAngle, 0);

                    // 持续平滑旋转
                    childTransform.rotation = Quaternion.Slerp(
                        childTransform.rotation,
                        currentTargetRotation,
                        GunBarrelRotateSpeed * Time.deltaTime
                    );
                }
            }
        }


        // --- 射击方向控制 ---
        Plane plane = new Plane(Vector3.up, transform.position);
        float enter = 0f;
        if (plane.Raycast(ray, out enter))
        {
            Vector3 hitPoint = ray.GetPoint(enter);
            Vector3 dir = hitPoint - transform.position;
            dir.y = 0; // 只在xOz平面
            if (dir.sqrMagnitude > 0.01f)
            {
                bulletSpawnPoint.transform.forward = dir.normalized;
            }
        }

        // 射击
        if (Input.GetMouseButtonDown(0) && Time.time - lastShootTime > shootCooldown)
        {
            Shoot();
            lastShootTime = Time.time;
        }
    }

    void AttachCamera()
    {
        // 获取主摄像机
        Camera mainCamera = Camera.main;

        // 如果摄像机有跟随脚本，设置目标为当前玩家
        if (cameraFollow == null)
            cameraFollow = mainCamera.GetComponent<CameraFollow>();

        if (cameraFollow != null)
        {
            cameraFollow.target = transform; // 设置为当前玩家的Transform
        }
    }
    void Shoot()
    {
        if (isDead) return;

        if (childTransform == null)
        {
            Debug.LogError("GunBarrel 子组件未找到，无法获取射击方向！");
            return;
        }

        // 获取炮管的前向向量（世界空间）
        Vector3 shootDirection = -childTransform.up;
        shootDirection = shootDirection.normalized;

        // 发送射击消息
        networkManager.SendShootMessage(bulletSpawnPoint.transform.position, shootDirection);
    }

    // 受到伤害
    public void TakeDamage(float amount, string attackerId = null)
    {
        if (isDead) return;

        // 播放受击特效
        if (hitEffect != null)
        {
            Instantiate(hitEffect, transform.position, Quaternion.identity);
        }

        // 只在本地玩家被击中时，向服务器发送hit消息
        if (isLocalPlayer && attackerId != null)
        {
            networkManager.SendHitMessage(attackerId, playerId, amount);
        }

        // 更新血量显示
        UpdateHealthUI();

        // 检查死亡
        if (health <= 0)
        {
            Die(attackerId);
        }
    }

    // 死亡处理
    public void Die(string killerId)
    {
        // 设置死亡状态
        isDead = true;

        // 播放死亡特效
        if (deathEffect != null)
        {
            Instantiate(deathEffect, transform.position, Quaternion.identity);
        }

        // 隐藏玩家模型
        foreach (Renderer r in GetComponentsInChildren<Renderer>())
        {
            r.enabled = false;
        }

        // 禁用碰撞
        foreach (Collider c in GetComponentsInChildren<Collider>())
        {
            c.enabled = false;
        }

        // 在GameManager中处理死亡逻辑（计分、复活等）
        if (gameManager != null && networkManager.isServer)
        {
            gameManager.HandlePlayerDeath(playerId, killerId);
        }
    }

    // 复活
    public void Respawn(Vector3 spawnPosition)
    {
        // 重置状态
        isDead = false;
        health = 100f;
        transform.position = spawnPosition;
        transform.rotation = Quaternion.identity;

        // 显示玩家模型
        foreach (Renderer r in GetComponentsInChildren<Renderer>())
        {
            r.enabled = true;
        }

        // 启用碰撞
        foreach (Collider c in GetComponentsInChildren<Collider>())
        {
            c.enabled = true;
        }

        // 播放复活特效
        if (respawnEffect != null)
        {
            Instantiate(respawnEffect, transform.position, Quaternion.identity);
        }

        // 更新UI
        UpdateUI();

        // 如果是本地玩家，同步位置
        if (isLocalPlayer)
        {
            networkManager.SendMoveMessage(transform.position, transform.eulerAngles.y);
        }
    }

    // 加分
    public void AddScore(int points)
    {
        score += points;
        UpdateUI();
    }

    // 设置队伍
    public void SetTeam(string newTeam)
    {
        team = newTeam;
        UpdateUI();
    }

    // 更新UI显示
    public void UpdateUI()
    {
        UpdateHealthUI();
    }

    // 更新血量UI
    public void UpdateHealthUI()
    {
        // 更新头顶血条
        RefreshHealthUI();
    }

    // 刷新血条UI
    public void RefreshHealthUI()
    {
        HealthUI ui = FindObjectOfType<HealthUI>();
        if (ui != null && ui.player == this)
        {
            ui.Refresh();
        }
    }
}